#!/usr/bin/perl
##
# @param $1 install home
# @param $2 delimiter
# @param $3 host
# @param $4 port
# @param $5 username
# @param $6 password
#
use strict;

sub getTimeStr
{
  my $time = shift(@_);
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);

  # $mon is between 0 and 11 from localtime function
  $mon ++;  
  $year += 1900;

  my $timestr = ${year}.'-'.${mon}.'-'.${mday}.' '.${hour}.':'.${min}.':'.${sec};

  return $timestr;
}

sub checkBackup
{
  my $method = shift(@_);
  my $host = shift(@_);
  my $port = shift(@_);
  my $tmpdir = shift(@_);

  my $homedir;
  @ARGV = ("/etc/passwd");
  while (<>) {
    if (/^mysql/) {
       $homedir = (split(/:/,$_))[5];
    }
  }
  if (!-d "$homedir") {
     exit;
  } 
#  my $homedir=`ls -d ~mysql`;
#  chomp($homedir);
  my $logdir=$homedir.'/dbadmin/logs';

  my $prefix=$logdir."/${host}_${port}_${method}";
  my $statfile=`ls -t ${prefix}*| head -1`;
  chomp($statfile);
  my $mtime = (stat ($statfile))[9];
  my $timestr = getTimeStr($mtime);

  my $lastcheckfile=$tmpdir."/${host}_${port}_${method}_status_file_last_modified_time";

  if ( -f $statfile )
  {
    open(my $fh, "<" , $statfile) or die "$0: can't open $statfile: $!";
    my @stat = <$fh>;
    close($fh);
    chomp(@stat);
    my($status,$size,$duration,$message) = split /\|/, $stat[0];

    # change unit of size from K to M
    $size /= 1024;

    open(my $fhlast, ">" , $lastcheckfile) or die "$0: can't open $lastcheckfile: $!";

    my $starttime;

    #### Backup has been ended if statfile is not empty.
    if ( @stat )
    {
      print " last index of stat = $#stat\n";
      $starttime = $mtime - $duration * 60;
    }
    else
    {
      $status='RUNNING';
      $duration = ( time() - $mtime ) / 60;
      $starttime = $mtime;
    }

    my $starttime_str = getTimeStr($starttime);
    my $em_result = "$method|$starttime_str|$status|$size|$duration|$message";

    print $fhlast getTimeStr($mtime);
    print $fhlast "\n";
    print $fhlast "status = $status\n";
    print $fhlast "em_result=$em_result\n";
    close($fhlast);

    print "em_result=$em_result\n";

  }

}


my ($MYSQL_HOME,$DELIM,$HOST,$PORT,$USER,$PASS) = @ARGV;
my $PARAM="";
$PARAM="$PARAM -h\"$HOST\"" if (defined($HOST) && $HOST ne "");
$PARAM="$PARAM -P\"$PORT\"" if (defined($PORT) && $PORT ne "");
$PARAM="$PARAM -u\"$USER\"" if (defined($USER) && $USER ne "");
$PARAM="$PARAM -p\"$PASS\"" if (defined($PASS) && $PASS ne "");

my $tmpdir="/tmp";
my $method="dump";
checkBackup($method,$HOST,$PORT,$tmpdir);

my $method="hotbak";
checkBackup($method,$HOST,$PORT,$tmpdir);

exit 0
